﻿using AppWebApi.Utilities.SM4;
using Newtonsoft.Json;

namespace AppWebApi.Models
{
    /// <summary>
    /// 接口统一响应模型
    /// </summary>
    public class ApiResult : ApiResult<object>
    {
        public static ApiResult Success(string msg)
        {
            return new ApiResult { success = true, msg = msg };
        }

        public static ApiResult Success(string msg, object data)
        {
            return new ApiResult { success = true, msg = msg, data = data };
        }

        public new static ApiResult Failure(string msg)
        {
            return new ApiResult { msg = msg };
        }

        public new static ApiResult Failure(int code)
        {
            return new ApiResult { code = code };
        }
    }

    /// <summary>
    /// 接口统一响应模型
    /// </summary>
    /// <typeparam name="T">业务数据</typeparam>
    public class ApiResult<T>
    {
        /// <summary>
        /// 业务返回类型
        /// </summary>
        public ApiResultType type { get; set; } = ApiResultType.General;
        /// <summary>
        /// 业务代码
        /// </summary>
        public int? code { get; set; }
        /// <summary>
        /// 业务信息
        /// </summary>
        public string msg { get; set; } = string.Empty;
        /// <summary>
        /// 业务是否成功
        /// </summary>
        public bool success { get; set; }
        /// <summary>
        /// 业务数据
        /// </summary>
        public T? data { get; set; }

        public static ApiResult<T> Success(T data)
        {
            return new ApiResult<T> { success = true, data = data };
        }

        public static ApiResult<T> Failure(T data)
        {
            return new ApiResult<T> { success = false, data = data };
        }

        public static ApiResult<T> Failure(string msg)
        {
            return new ApiResult<T> { msg = msg };
        }

        public static ApiResult<T> Failure(int code)
        {
            return new ApiResult<T> { code = code };
        }

    }

    public enum ApiResultType
    {
        /// <summary>
        /// 普通
        /// </summary>
        General = 0,

        /// <summary>
        /// 输入模型验证失败
        /// </summary>
        InvalidModelState = 20,

    }

    public static class ApiResultExtensions
    {
        public static ApiResult Encrypt(this ApiResult result)
        {
            var crypto = new Sm4Crypto { Data = Sm4Crypto.UrlEncode(JsonConvert.SerializeObject(result.data)) };
            result.data = Sm4Crypto.EncryptCBC(crypto);
            return result;
        }
    }
}
